import React, { memo, useEffect } from "react";
import { login } from "../api/user";
import { Button, Form, Input, message } from "antd";
import {useNavigate} from 'react-router-dom'
const Login = memo(() => {
  const navigate = useNavigate()
  //表单的校验规则
  const validateMessages = {
    required: "${label}是必填项!",
    types: {
      number: "${label}不是合法的数字!",
    },
    string: {
      min: "${label}至少应该是${min}位长度的字符串",
    },
  };
  //点击登录按钮的表单校验函数
  let doLogin = async (values) => {
    //在 Ant Design 中，loginForm.validateFields() 是一个用于表单验证的方法。
    //该方法会检查表单中的每个字段是否满足预定义的验证规则
    loginForm.validateFields().then(async (values) => {
        const res = await login(values)
        if(!res.data.success){
          return message.error('登录失败')
        }
        const token = res.data.data.token
        localStorage.setItem("token", token)
        if(token){
          navigate('/todo3')
        }
    }).catch(error => {
      
    })
  };
  const [loginForm] = Form.useForm();
  return (
    <div>
      <Form
        form={loginForm}
        onFinish={doLogin}
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        style={{
          maxWidth: 600,
        }}
        autoComplete="off"
        validateMessages={validateMessages}
      >
        <Form.Item
          label="用户名/账号"
          name="username"
          rules={[
            {
              required: true,
            },
            {
              type: "string",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
            },
            {
              type: "string",
              min: 6,
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit" onClick={doLogin}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
});

export default Login;
